package cn.jietuo.juc.c_009_interview2;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/8
 * @description: 使用wait notify来实现
 */
public class T02_MyContainer1<T>{

    private final static int MAX = 10;

    private int count = 0;

    private LinkedList<T> data = new LinkedList<>();


    public synchronized void put(T t) {
        while (data.size() == MAX) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        data.add(t);
        ++count;
        this.notifyAll();
    }

    public synchronized T get() {
        T t = null;
        while (data.size() <= 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t = data.removeFirst();
        --count;
        this.notifyAll();
        return t;
    }

    public synchronized int getCount() {
        return count;
    }

    public static void main(String[] args) {

        
        T02_MyContainer1<String> myContainer = new T02_MyContainer1<>();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10; j++) {
                    String s = myContainer.get();
                    System.out.println(Thread.currentThread().getName() + "，获取到数据：" + s);
                }

            }, "customer" + i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 20; j++) {
                    myContainer.put(Thread.currentThread().getName() + "--" + j);
                    System.out.println(Thread.currentThread().getName() + "，添加数据：" + Thread.currentThread().getName() + "--" + j);
                }
            }, "producer" + i).start();
        }
    }


}
